package com.tz.controller;

import com.tz.entity.Research;
import com.tz.entity.User;
import com.tz.service.LoginService;
import com.tz.service.ResearchService;
import com.tz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/login")
//把放入到model中的数据放入到session中
@SessionAttributes("user")
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    ResearchService researchService;
    @Autowired
    UserService userService;

    @RequestMapping("/prelogin")
    public String preLogin(HttpServletRequest request, String info, Model model, @CookieValue(value = "user", required = false) String userInfo) {

        if (userInfo != null) {
            String[] infoArr = userInfo.split(":");
            model.addAttribute("username", infoArr[0]);
            model.addAttribute("password", infoArr[1]);
        }
        model.addAttribute("info", info);
        HashMap<Long, int[]> obj = (HashMap<Long, int[]>) request.getServletContext().getAttribute("countMap");
        //加锁防止并发
        List<Research> researchs = new ArrayList<>();
        for (Long id : obj.keySet()) {
            researchs.add(researchService.findById(id));
        }
        model.addAttribute("researchs", researchs);


        return "login";
    }

    @RequestMapping("/logout")
    public String logout(SessionStatus sessionStatus) {
        sessionStatus.setComplete();
        return "redirect:/login/prelogin";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, Model model, String username, String password) {
        System.out.println(username);
        System.out.println(password);
        User user = userService.login(username, password);

        //配置了@SessionAttributes()后,放入model中的数据会同等放入到session中

        //判断
        if (user != null) {
            model.addAttribute("user", user);
            //登陆成功,则跳转到下一个页面
            return "redirect:/user/index";
        } else {
            //登陆失败,则停留在登陆页面并且作提示
            model.addAttribute("info", 1);
            return "redirect:/login/prelogin";
        }

    }
}
